<template>
  <div id="area" >
    <div style="width: 96%;    box-shadow: 3px 3px 3px 1px rgba(224, 200, 209, 0.2);margin:80px  0 50px  2%;display: flex;flex-direction: column;align-items: center;">
      <el-table
        border
        stripe
        row-id="resourceID"
        row-key="resourceID"
        ref="searchTable"
        :data="tableList"
        element-loading-text="加载中，请稍后..."
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        class="table temp-table"
        style="width: 100%"
        :max-height="450"
        :header-cell-style="{background:'#F5F5F5'}"
        highlight-hover-row
      >
        <el-table-column label="序号" width="50px" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column label="巡检站点"  align="center" prop="platformName"></el-table-column>
        <el-table-column label="巡检业务KFC"  prop="executeTime">
          <template slot-scope="scope">
            <div>
              <div v-if="scope.row.kfc.status == 'FAILED'"><span>结果：</span><span>失败</span><span style="display: inline-block;width: .7rem;height:.7rem;border-radius:50%;background-color:red;margin-left: .5rem"></span> </div>
              <div style="" v-if="scope.row.kfc.status == 'SUCCESS'"><span>结果：</span><span>正常</span> <span style="display: inline-block;width: .7rem;height:.7rem;border-radius:50%;background-color:greenyellow;margin-left: .5rem"></span></div>
              <div>更新时间：<el-tag v-if="scope.row.kfc.time">{{scope.row.kfc.time}}</el-tag></div>
              <div><span>通过率：</span><span v-if="scope.row.kfc.passRate">{{scope.row.kfc.passRate*100}}%</span></div>
            </div>

          </template>
        </el-table-column>

        <el-table-column label="巡检业务PH"   prop="executeTime">
          <template slot-scope="scope">
            <div>
              <div v-if="scope.row.ph.status == 'FAILED'"><span>结果：</span><span>失败</span><span style="display: inline-block;width: .7rem;height:.7rem;border-radius:50%;background-color:red;margin-left: .5rem"></span> </div>
              <div style="" v-if="scope.row.ph.status == 'SUCCESS'"><span>结果：</span><span>正常</span> <span style="display: inline-block;width: .7rem;height:.7rem;border-radius:50%;background-color:greenyellow;margin-left: .5rem"></span></div>
              <div>更新时间：<el-tag v-if="scope.row.ph.time">{{scope.row.ph.time}}</el-tag></div>
              <div><span>通过率：</span><span v-if="scope.row.ph.passRate">{{scope.row.ph.passRate*100}}%</span></div>
            </div>
          </template>
        </el-table-column>


      </el-table>
    </div>

    <searchTablePagination
      ref="searchtable"
      :searchFormData="searchFormData"
      :has-form="tableConfig.hasForm"
      :loading="tableLoading"
      :table-config="tableConfig"
      @pieOp="pieOp"
      @ec="ec"
      @handleSelectionChange="handleSelectionChange"
    >
      <template slot="expand" slot-scope="scope">
       <div style="margin-left: 5rem;width: 95%;display: flex">
         <div style="width: 73%;">
           <el-descriptions class="margin-top" :column="2" size="small" border>

             <el-descriptions-item>
               <template slot="label">
                 工作空间名称
               </template>
               {{ scope.row.workspaceName}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 测试计划名称
               </template>
               {{ scope.row.testPlanName}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 项目名称
               </template>
               {{ scope.row.projectName}}
             </el-descriptions-item>
             <el-descriptions-item>
               <template slot="label">
                 报告平台名称
               </template>
               {{ scope.row.platformName}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 计划创建者
               </template>
               {{ scope.row.creator}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 执行结果
               </template>
               <el-tag> {{ scope.row.status}} </el-tag>
             </el-descriptions-item>
             <el-descriptions-item>
               <template slot="label">
                 执行时长（毫秒）
               </template>

               <el-tag>{{ scope.row.costTime}}</el-tag>
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 用例个数
               </template>
               <el-tag>{{ scope.row.caseCount}}</el-tag>
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 成功个数
               </template>
               {{ scope.row.passCount}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 失败数
               </template>
               {{ scope.row.failedCount}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 用例异常个数
               </template>
               {{ scope.row.brokenCount}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 未执行用例个数
               </template>
               {{ scope.row.skippedCount}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 未知原因识别个数
               </template>
               {{ scope.row.unknownCount}}
             </el-descriptions-item>

          <!--   <el-descriptions-item>
               <template slot="label">
                 未知原因识别个数
               </template>
               {{ scope.row.unknownCount}}
             </el-descriptions-item>-->
             <el-descriptions-item>
               <template slot="label">
                 执行个数
               </template>
               {{ scope.row.executeCount}}
             </el-descriptions-item>


             <el-descriptions-item>
               <template slot="label">
                 执行率
               </template>
               {{ scope.row.executeRate}}
             </el-descriptions-item>
             <el-descriptions-item>
               <template slot="label">
                 执行方式
               </template>
               {{ scope.row.triggerMode}}
             </el-descriptions-item>

             <el-descriptions-item>
               <template slot="label">
                 触发方式
               </template>
               {{ scope.row.runMode}}
             </el-descriptions-item>
             <el-descriptions-item>
               <template slot="label">
                 MS执行环境
               </template>
               {{ scope.row.projectEnvMap}}
             </el-descriptions-item>
             <el-descriptions-item>
               <template slot="label">
                 场景执行概况
               </template>
               {{ scope.row.apiScenarioResult}}
             </el-descriptions-item>
             <el-descriptions-item>
               <template slot="label">
                 入库时间
               </template>
               {{ scope.row.insertTime}}
             </el-descriptions-item>
           </el-descriptions>
         </div>
         <div class="piechart">
            <div style="width: 20rem;height: 20rem">
              <div :id="'pieChart_' + scope.row.id" class="echart" style="width: 20rem;height: 20rem"></div>
            </div>
         </div>
       </div>
      </template>
      <template slot="id" slot-scope="scope">
        <div style="display: flex">
          <!--<div>{{scope.row.id}} </div>-->
          <div style="margin-left: 10px;" v-if="scope.row.platformName=='Pytest'">
            <el-tag  style="background-color:sandybrown;">P</el-tag>
          </div>
          <div  style="margin-left: 10px;" v-if="scope.row.platformName=='MeterSphere'">
            <el-tag >M</el-tag>
          </div>
        </div>
      </template>

      <template slot="tableOperator" slot-scope="scope">

        <div style="display: flex;justify-content: center;align-items: center">
          <el-button size="mini" @click="reportDetail(scope.row)"> 报告详情</el-button>
          <el-button  type="primary" size="mini" @click="toHT(scope.row)"> 历史执行记录</el-button>
        </div>
      </template>

    </searchTablePagination>
  </div>
</template>

<script>
  import * as echarts from "echarts";
  import searchTablePagination from "./searchTable/searchTablePagination"

  import domain from '../../../domain.js'
  const base = domain.target

  export default {
    name: 'DemandManagement',
    components: {
      searchTablePagination,
    },
    created () {
      console.log("created")

      this.$nextTick(()=>{
        console.log(document.querySelector("#area").clientHeight)
        let H = document.querySelector("#area").clientHeight
        if (H>300){
          this.tableConfig.tableHeight = H+320
        }else{
          this.tableConfig.tableHeight = H+220
        }
      })
      // this.getAllWorkspaces()
    },
    mounted() {
      this.gettableData()
    },
    activated() {
      console.log("activated")
    },
    data () {
      return {
        tableList:[],
        platformList:[
          {
            textName:"MeterSphere",
            value:"MeterSphere"
          },
          {
            textName:"Pytest",
            value:"Pytest"
          },
        ],
        selectedRows:[],
        taskModalVisible:false,
        ImportDemandModalVisible:false,
        dialogTitle:"新增",
        rowData:{},// 需求对象数据
        tableLoading:false,
        tableData:[],
        statusList:[],
        searchFormData: {
          // platformName:"",
          // workspaceName:"",
          // projectName:"",
          reportName:"",


        },

        tableConfig: {
          tableHeight:0,
          requestUrl:`${base}/join/reports/inspection/list`,
          // requestUrl:``,
          hasForm:false,
          isRadio: false,
          topOperate: true,
          isIndex:true,
          columnConfig: [
            { isSlot:true,expand:true,fixed:"left"},
            { prop: 'id', label: '平台类型',width:70, isSlot: "id"},
            { prop: 'reportName', label: '报告名称',width:250  },
            { prop: 'passRate', label: '通过率',width:150, },
            { prop: 'createTime', label: '测试计划创建时间' },
            { prop: 'endTime', label: '测试计划结束时间' },
            { prop: 'systemId', label: '系统id' },
            { prop: 'systemName', label: '系统名称',width:150, },
            { prop:"operator",label:"操作",width:230} // fixed:"right",
          ]
        },
        projectsList:[],
        workspacesList:[],
      }
    },
    methods: {
      gettableData(){
        // /join/reports/inspection/table/list
        let url = `${base}/join/reports/inspection/table/list`
        this.$get(url,{}).then((res)=>{
          if (res &&res.data.code==20000){
            this.tableList = res.data.obj || []
          }
        })
      },
      // getAllWorkspaces(){
      //   let url = `${base}/join/workspaces`
      //   this.$get(url,{}).then((res)=>{
      //     if (res &&res.data.code==20000){
      //       this.workspacesList = res.data.obj || []
      //     }
      //   })
      // },
      // getProjectsByWorkspaceName(val){
      //   let url = `${base}/join/projects`
      //   let params = {
      //     workspaceName:val
      //   }
      //   this.$get(url,{params}).then((res)=>{
      //     if (res &&res.data.code==20000){
      //       this.projectsList = res.data.obj || []
      //
      //     }
      //   })
      // },
      // platformNameChange(val){
      //   console.log(val)
      //   if (val == "MeterSphere"){
      //     this.searchFormData.workspaceName = ""
      //     this.searchFormData.projectName = ""
      //   }
      // },
      renderPieChart(pass, containerId) {
        let fail;
        if (pass ==0){
          fail=1
        }else{
          pass = parseFloat(pass) / 100;
          fail = (1-pass).toFixed(2)
        }
        console.log("containerId",containerId)
        let dataArr = [
          {
            value:pass,
            name:"通过率",
            itemStyle: { color: '#67c23a' }
          },
          {
            value:fail,
            name:"失败率",
            itemStyle: { color: 'red' }
          }
        ]
        const chart = echarts.init(document.getElementById(containerId));
        console.log("chart",chart)
        console.log("dataArr",dataArr);
        if (chart){
          const option = {
            title: {
              text: '通过率/失败率',
              // subtext: 'Fake Data',
              left: 'center',
              textStyle:{
                fontStyle:"normal",
                fontSize:"14",
              },
            },
            label: {
              show: true,
              position: 'top',
              // color: 'rgba(119,167,255,1)',
              fontSize: 12,
              textAlign: 'center',
            },
            tooltip: {
              trigger: 'item',
               formatter:function(params){
                 // console.log("params",params)
                 return `${params.name}为${params.value*100}% `
               },
              textStyle: {
                color: "rgba(212, 232, 254, 1)",
                // fontSize: fontChart(0.24),
              },
            },
         /*   legend: {
              orient: 'vertical',
              left:"left",
              bottom: 'top',

            },*/
            series: [
              {
                name: '通过率',
                type: 'pie',
                radius: '50%',
                data:dataArr,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          chart.setOption(option);
        }

      },

      reportDetail(row){

        if (row.platformName == "MeterSphere"){
          let resultArr = JSON.parse(row.apiScenarioResult)
          let errorCount = 0
          let successCount = 0
          let pendingCount = 0
          let stoppedCount = 0
          resultArr.forEach((item)=>{
            if (item.status=="ERROR"){
              errorCount = item.count
            }
            if (item.status=="SUCCESS"){
              successCount = item.count
            }

            if (item.status=="PENDING"){
              pendingCount = item.count
            }

            if (item.status=="STOPPED"){
              stoppedCount = item.count
            }

          })
          this.$router.push({
            path:"/onlineDetail",
            query:{
              reportId:row.reportId,
              reportName:row.reportName,
              successCount,
              errorCount,
              pendingCount,
              stoppedCount,
            }
          })
        }

        if (row.platformName == 'Pytest'){
          this.$router.push({
            path:"/pydetail",
            query:{
              reportId:row.reportId,
              reportName:row.reportName,
              brokenCount:row.brokenCount,
              failedCount:row.failedCount,
              skippedCount:row.skippedCount,
              passCount:row.passCount,
              unknownCount:row.unknownCount,

            }
          })
        }

      },

      toHT(row){
        // testPlanName=&platformType= &page=&pageSize=
        this.$router.push({
          path:"/historyTable",
          query:{
            testPlanName: row.testPlanName,
            platformName: row.platformName,
            sid:row.systemId,
            sname:row.systemName,
            projectName:row.projectName,
            workspaceName:row.workspaceName,

          }
        })
      },

      getTemplateRow(val){

      },
      handleSelectionChange(rows){
        console.log("选中的数据",rows)
        this.selectedRows = rows
      },
      pieOp(data){
        // this.tableList = data
        // console.log(this.tableList);
        // this.tableList.forEach((item)=>{
        //   let strings = item.testPlanName.split("-");
        //   this.$set(item,"zhandian",strings[0])
        // })

        // data.forEach((row, index) => {
        //   console.log("row",row)
        //   this.renderPieChart(row.passRate, 'pieChart_' + row.id);
        //   // this.renderPieChart(row.passRate, 'pieChart' );
        // },3000);
      },
      ec(row,rows){
        // console.log(row,rows)
        this.$nextTick(()=>{
          this.renderPieChart(row.passRate, 'pieChart_'+ row.id );

        })
      },


      addTask (row) {
        console.log("row",row)
        this.rowData = row
        if (this.rowData == null){
          this.$router.push({
            path:"/task",
          })
        }else{
          this.$router.push({
            path:"/task",
            query:{
              row
            }
          })
        }

      },


      chakan(row){
        console.log(row)
        this.$router.push({
          path:"/process",
          query:{
            row
          }
        })
      }
    },

    computed: {
    /*  testSystemList(){
        return this.$store.getters.chosenSystemList
      },
      systemID(){
        return this.$store.getters.activeSystem
      }*/
    },
    watch: {
  /*    systemID:{
        immediate:true,
        handler(newVal,oldVal){
          this.searchFormData.sid = newVal
          setTimeout(()=>{
            this.$refs.searchtable.handleSearch() //
          })
        }
      }*/
    },
  }

</script>

<style scoped lang="scss">
  #area{

  }
  .demo-table-expand {
    /*font-size: 0;*/
  }
  .demo-table-expand label {
    width: 120px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {

    width: 40%;
  }

  ::v-deep .el-descriptions-item__label.is-bordered-label{
    width: 160px;
  }
  .piechart{
    flex:1;
    margin-left: 10px;
    border: 1px solid #e8e8e8;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #e8e8e8;
  }
  /*表格换行显示*/
  ::v-deep .el-table thead {
    height: 50px;
    color: #000;
    background-color: red;
    font-weight: bold;
  }
</style>
